// pages/event-add/index.js
import {
    curTimeAll,
    getAge
} from '../../third-utils/time/index.js';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        categroyList: [],
        curEventId:'',
        curCate: 0,
        endDate: '',
        wn_type: [],
        recordDate: '',
        typeIndex: 20,
        imageAttr: [],
        cateType1Attr: ['计时', '手动输入'],
        cateType1Index: 0,
        curTimeStart: '',
        leftTime: 0,
        rightTime: 0,
        leftTimeValue: 14,
        rightTimeValue: 14,
        timeSlot: [],
        wn_pflx: [],
        firstDate: '',
        wn_brand: [],
        pflxIndex: '',
        brandIndex: '',
        timeInterval: null,
        firstDateDisabled: false,
        brandOther: '',
        milkTypeOther: '',
        wn_zzff: ['是', '否'],
        zzIndex: '',
        pflxIndex1: '',
        wn_shao: [],
        shaoIndex: '',
        shaoIndex2: '',
        brandIndex2: '',
        totalTimeNum: '',
        birthday: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(e) {

        this.setData({
            birthday: getAge('2023-05-19')
        })
        wx.request({
            url: 'https://babyplanet.isv-dev.youzan.com/api/recordType/findList',
            data: {
                parentId: e.cateId
            },
            method: 'post',
            success: (res) => {
                if (res.data.code == 200) {
                    this.setData({
                        categroyList: res.data.data
                    })
                    if (e.typeId) {

                        this.data.categroyList.some((item, index) => {
                            if (item.id == e.typeId) {

                                this.setData({
                                    curCate: index
                                })
                            }
                        })
                    }
                    if(e.id){
                        this.setData({
                            curEventId:e.id
                        })
                        this.getEventInfo(e.id)
                    }

                }
            }
        })


        for (let i = 0; i <= 10; i += 0.5) {
            this.data.wn_shao.push(i)
        }
        this.setData({
            wn_shao: this.data.wn_shao
        })
        for (let i = 1; i < 60; i++) {
            this.data.timeSlot.push(i)
        }
        this.setData({
            timeSlot: this.data.timeSlot
        })

        // for(let i=1;i<100;i++){
        //     this.data.wn_type.push(i)
        // }
        for (let i = 0; i < 500; i += 5) {
            this.data.wn_type.push(i)
        }
        this.setData({
            wn_type: this.data.wn_type,
            recordDate: curTimeAll
        })
        this.initData()
    },
    getFirstTime() {
        console.log(this.data.pflxIndex, this.data.brandIndex)
        if (this.data.pflxIndex == '' || this.data.brandIndex == '') {
            return
        }

        this.setData({
            firstDateDisabled: false,
            firstDate: ''
        })
        wx.request({
            url: 'https://babyplanet.isv-dev.youzan.com/api/babyRecord/getFirstRecordForPFN',
            data: {
                babyId: 32,
                typeId: 9,
                milkType: this.data.wn_pflx.opts[this.data.pflxIndex].name,
                brand: this.data.wn_brand.opts[this.data.brandIndex].name,
            },
            method: 'post',
            success: (res) => {
                if (res.data.code == 200) {

                    if (res.data.data && res.data.data.detail.firstDate) {
                        this.setData({
                            firstDateDisabled: true,
                            firstDate: res.data.data.detail.firstDate
                        })
                        this.getTimeNum()
                    }
                }
            }
        })
    },

    getEventInfo(id) {

        wx.request({
            url: 'https://babyplanet.isv-dev.youzan.com/api/babyRecord/view',
            data: {
                id: id
            },
            method: 'get',
            success: (res) => {
                if (res.data.code == 200) {
                    this.setDefault(res.data.data.detail)
                }
            }
        })
    },
    handleDel(){
        
    let that=this
    wx.showModal({
      title: '提示',
      content: '确定删除该记录吗？',
      success (res) {
        if (res.confirm) {
          wx.request({
            url: 'https://babyplanet.isv-dev.youzan.com/api/babyRecord/delete',
            data: {
              id:that.data.curEventId
            },
            method: 'post',
            success: (res) => {
              if (res.data.code == 200) {

                wx.showToast({
                    title: '删除成功！',
                    icon: 'none',
                    duration: 1500 //持续的时间
                })
                setTimeout(() => {
                    wx.navigateBack()
                }, 1500)
              }
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
    },
    setDefault(curData) {
        this.setData({
            milkTypeOther: curData.milkTypeOther,
            milkTypeOther2: curData.milkTypeOther2,
            brandOther: curData.brandOther,
            brandOther2: curData.brandOther2,
        })
        if(this.data.curEventId){
            
        this.setData({
            recordDate: curData.recordDate,
            description:curData.description,
            cateType1Index:1,
            imageAttr:curData.picture?(curData.picture).split(','):''
        })
        }
        if (curData.type) {
            for (let i in this.data.wn_type) {
                if (this.data.wn_type[i] == curData.type.split('ml')[0]) {
                    this.setData({
                        typeIndex: i
                    })
                }
            }
        }

        if (curData.milkType) {
            for (let i in this.data.wn_pflx.opts) {
                if (this.data.wn_pflx.opts[i].name == curData.milkType) {
                    this.setData({
                        pflxIndex: i
                    })
                }
            }
        }
        if (curData.milkType2) {
            for (let i in this.data.wn_pflx.opts) {
                if (this.data.wn_pflx.opts[i].name == curData.milkType2) {
                    this.setData({
                        pflxIndex1: i
                    })
                }
            }
        }
        if (curData.brand) {
            for (let i in this.data.wn_brand.opts) {
                if (this.data.wn_brand.opts[i].name == curData.brand) {
                    this.setData({
                        brandIndex: i
                    })
                }
            }
        }
        if (curData.proportion) {
            for (let i in this.data.wn_shao) {
                if (this.data.wn_shao[i] == curData.proportion) {
                    this.setData({
                        shaoIndex: i
                    })
                }
            }
        }
        if (curData.proportion2) {
            for (let i in this.data.wn_shao) {
                if (this.data.wn_shao[i] == curData.proportion2) {
                    this.setData({
                        shaoIndex2: i
                    })
                }
            }
        }
        if (curData.proportion) {
            for (let i in this.data.wn_brand.opts) {
                if (this.data.wn_brand.opts[i].name == curData.brand2) {
                    this.setData({
                        brandIndex2: i
                    })
                }
            }
        }
        if (curData.firstDate) {
            this.setData({
                firstDateDisabled: true,
                firstDate: curData.firstDate
            })
            this.getTimeNum()
        }
    },
    getCurData(id) {

        wx.request({
            url: 'https://babyplanet.isv-dev.youzan.com/api/babyRecord/findPage',
            data: {
                babyId: 32,
                pageSize: 1,
                typeId: id
            },
            method: 'post',
            success: (res) => {
                if (res.data.code == 200) {
                    if (res.data.data.list.length > 0) {
                        let curData = {}
                        curData = res.data.data.list[0].detail
                        this.setDefault(curData)
                    }
                }
            }
        })
    },
    slider2change() {},
    select(e) {
        this.setData({
            [e.currentTarget.dataset.key]: e.currentTarget.dataset.index
        })
    },
    bindDateChange(e) {
        this.setData({
            [e.currentTarget.dataset.key]: e.detail.value
        })
        if (e.currentTarget.dataset.key == 'firstDate') {
            this.getTimeNum()
        }
    },
    getTimeNum() {
        console.log(2322332)
        if (!this.data.firstDate || !this.data.recordDate) {
            return
        }
        let time1 = new Date(this.data.recordDate).getTime();
        let time2 = new Date(this.data.firstDate).getTime();
        let time = parseInt((time1 - time2) / (1000 * 3600 * 24));
        this.setData({
            totalTimeNum: time + '天'
        })

    },
    getEndTime() {

        let now1 = new Date(this.data.recordDate.replace(/-/g, '/')).getTime() + (this.data.leftTime + this.data.rightTime) * 1000;
        console.log(now1, 121122)
        let now = new Date(now1);
        let year = now.getFullYear(); // 得到年份
        let month = now.getMonth() + 1; // 得到月份
        let date = now.getDate(); // 得到日期
        let hour = now.getHours(); // 得到小时
        let min = Number(now.getMinutes()) <= 9 ? ('0' + now.getMinutes()) : now.getMinutes(); // 得到分钟
        let curTimeAll = year + "-" + month + "-" + date + " " + hour + ":" + min
        this.setData({
            endDate: curTimeAll
        })
    },
    startTime(e) {
        let val = e.currentTarget.dataset.key == this.data.curTimeStart ? '' : e.currentTarget.dataset.key

        clearInterval(this.data.timeInterval);
        if (val !== '') {
            let curkey = e.currentTarget.dataset.key + 'Time'
            console.log(curkey, 1212)
            this.data.timeInterval = setInterval(() => {
                this.data[curkey] += 1
                console.log(this.data[curkey], 1212)
                this.setData({
                    [curkey]: this.data[curkey]
                })
                this.getEndTime()
            }, 1000);
        }
        this.setData({
            curTimeStart: val
        })
    },
    countDown(countDown) {
        console.log(countDown, 1212)
        var secondTime = parseInt(countDown); // 秒
        var minuteTime = 0; // 分
        var hourTime = 0; // 小时
        if (secondTime >= 60) {
            minuteTime = parseInt(secondTime / 60);
            secondTime = parseInt(secondTime % 60);
            if (minuteTime >= 60) {
                hourTime = parseInt(minuteTime / 60);
                minuteTime = parseInt(minuteTime % 60);
            }
        }
        var hour = hourTime <= 9 ? '0' + hourTime : hourTime;
        var minutes = minuteTime <= 9 ? '0' + minuteTime : minuteTime;
        var second = secondTime <= 9 ? '0' + secondTime : secondTime;
        var val = minutes + ':' + second
        return val
    },
    bindChange(e) {
        console.log(e.detail.value[0], 121)
        this.setData({
            [e.currentTarget.dataset.key]: e.detail.value[0]
        })
    },
    formSubmit(e) {
        clearInterval(this.data.timeInterval);
        console.log(e, 12122)
        let post = {
            babyId: 32,
            typeId: this.data.categroyList[this.data.curCate].id,

        }

        if (this.data.curCate == 0) {
            post.detail = {
                startTime: this.data.recordDate,
                endTime: '2023-06-11 12:35',
                type: this.data.cateType1Index == 0 ? '计时' : '手动输入',
                leftTime: this.countDown(this.data.leftTime),
                rightTime: this.countDown(this.data.rightTime),
                totalTime: this.countDown(this.data.leftTime + this.data.rightTime),
                description: e.detail.value.description,
                picture: String(this.data.imageAttr)
            }
            if (this.data.cateType1Index == 0) {

                if ((this.data.leftTime + this.data.rightTime) <= 0) {
                    wx.showToast({
                        title: '请记录喂奶时长！',
                        icon: 'none',
                        duration: 1500 //持续的时间
                    })
                    return
                }
            }
            if (this.data.cateType1Index == 1) {

                post.detail.leftTime = this.data.timeSlot[this.data.leftTimeValue]
                post.detail.rightTime = this.data.timeSlot[this.data.rightTimeValue]
                post.detail.totalTime = this.data.timeSlot[this.data.leftTimeValue] + this.data.timeSlot[this.data.rightTimeValue]
            }
        } else if (this.data.curCate == 1) {

            if (this.data.typeIndex == '') {
                wx.showToast({
                    title: '请选择喂奶量！',
                    icon: 'none',
                    duration: 1500 //持续的时间
                })
                return
            }
            post.detail = {
                recordDate: this.data.recordDate,
                type: this.data.wn_type[this.data.typeIndex] + 'ml',
                description: e.detail.value.description,
                picture: String(this.data.imageAttr)
            }

        } else if (this.data.curCate == 2) {

            if (this.data.typeIndex == '') {
                wx.showToast({
                    title: '请选择喂奶量！',
                    icon: 'none',
                    duration: 1500 //持续的时间
                })
                return
            }
            if (this.data.pflxIndex == '') {
                wx.showToast({
                    title: '请选择配方类型！',
                    icon: 'none',
                    duration: 1500 //持续的时间
                })
                return
            }
            if (this.data.brandIndex == '') {
                wx.showToast({
                    title: '请选择品牌',
                    icon: 'none',
                    duration: 1500 //持续的时间
                })
                return
            }
            if (this.data.firstDate == '') {
                wx.showToast({
                    title: '请选择第一次使用时间',
                    icon: 'none',
                    duration: 1500 //持续的时间
                })
                return
            }
            post.detail = {
                recordDate: this.data.recordDate,
                type: this.data.wn_type[this.data.typeIndex] + 'ml',
                milkType: this.data.wn_pflx.opts[this.data.pflxIndex].name,
                brand: this.data.wn_brand.opts[this.data.brandIndex].name,
                milkTypeOther: e.detail.value.milkTypeOther,
                brandOther: e.detail.value.brandOther,
                firstDate: this.data.firstDate,
                totalTime: this.totalTimeNum,
                description: e.detail.value.description,
                picture: String(this.data.imageAttr)
            }

        } else if (this.data.curCate == 3) {

            if (this.data.typeIndex == '') {
                wx.showToast({
                    title: '请选择喂奶量！',
                    icon: 'none',
                    duration: 1500 //持续的时间
                })
                return
            }
            if (this.data.pflxIndex1 == '') {
                wx.showToast({
                    title: '请选择转奶类型！',
                    icon: 'none',
                    duration: 1500 //持续的时间
                })
                return
            }
            if (this.data.brandIndex2 == '') {
                wx.showToast({
                    title: '请选择品牌',
                    icon: 'none',
                    duration: 1500 //持续的时间
                })
                return
            }
            if (this.data.shaoIndex2 == '') {
                wx.showToast({
                    title: '请选择勺数',
                    icon: 'none',
                    duration: 1500 //持续的时间
                })
                return
            }
            post.detail = {
                recordDate: this.data.recordDate,
                type: this.data.wn_type[this.data.typeIndex] + 'ml',
                milkType: this.data.wn_pflx.opts[this.data.pflxIndex].name,
                milkType2: this.data.wn_pflx.opts[this.data.pflxIndex1].name,
                brand: this.data.wn_brand.opts[this.data.brandIndex].name,
                brand2: this.data.wn_brand.opts[this.data.brandIndex2].name,
                milkTypeOther: e.detail.value.milkTypeOther,
                milkTypeOther2: e.detail.value.milkTypeOther2,
                brandOther: e.detail.value.brandOther,
                brandOther2: e.detail.value.brandOther2,
                proportion: this.data.wn_shao[this.data.shaoIndex],
                proportion2: this.data.wn_shao[this.data.shaoIndex2],
                symptom: this.data.wn_zzff[this.data.zzIndex],
                description: e.detail.value.description,
                picture: String(this.data.imageAttr)
            }

        }

        let apiUrl='https://babyplanet.isv-dev.youzan.com/api/babyRecord/add'
        if(this.data.curEventId){
            apiUrl="https://babyplanet.isv-dev.youzan.com/api/babyRecord/update"
            post.id=this.data.curEventId
        }
        wx.request({
            url: apiUrl,
            data: post,
            method: 'post',
            success: (res) => {
                console.log(res, 122)
                if (res.data.code == 200) {

                    wx.showToast({
                        title: '保存成功！',
                        icon: 'none',
                        duration: 1500 //持续的时间
                    })
                    setTimeout(() => {
                        wx.navigateBack()
                    }, 1500)
                } else {
                    wx.showToast({
                        title: res.data.msg,
                        icon: 'none',
                        duration: 2000 //持续的时间
                    })
                }
            }
        })
    },

    pickerChangeType(e) {
        console.log(e, 21)
        this.setData({
            [e.currentTarget.dataset.key]: e.detail.value
        })
        if (this.data.curCate == 2) {

            this.getFirstTime()
        }
    },
    changeIndex(e) {
        if(this.data.curEventId){
            wx.showToast({
                title: '编辑记录不可切换类型！',
                icon: 'none',
                duration: 1500 //持续的时间
            })
            return
        }
        this.setData({
            [e.currentTarget.dataset.key]: e.currentTarget.dataset.index
        })

        if (e.currentTarget.dataset.key == 'curCate') {

            this.getCurData(this.data.categroyList[e.currentTarget.dataset.index].id)
        }
    },
    delImg(e) {
        this.data.imageAttr.splice(e.currentTarget.dataset.index, 1)
        this.setData({
            imageAttr: this.data.imageAttr
        })
    },
    addImg() {
        wx.chooseImage({
            count: 9,
            success: (chooseImageRes) => {
                console.log(chooseImageRes)
                const tempFilePaths = chooseImageRes.tempFilePaths;
                tempFilePaths.some((item) => {
                    wx.uploadFile({
                        url: 'https://babyplanet.isv-dev.youzan.com/common/image/upload', //仅为示例，非真实的接口地址
                        filePath: item,
                        fileType: 'image',
                        name: 'file',
                        headers: {
                            'Accept': 'application/json',
                            'Content-Type': 'multipart/form-data',
                        },
                        success: (uploadFileRes) => {
                            let res = JSON.parse(uploadFileRes.data)
                            if (res.code == 200) {
                                this.data.imageAttr.push(res.data.imageUrl)
                                this.setData({
                                    imageAttr: this.data.imageAttr
                                })
                            }
                        },
                    });
                })
            }
        });
    },
    initData() {
        let codeAttr = ['wn_pflx', 'wn_brand']
        codeAttr.some(item => {
            wx.request({
                url: 'https://babyplanet.isv-dev.youzan.com/api/selectConfig/view',
                data: {
                    code: item
                },
                method: 'get',
                success: (res) => {
                    if (res.data.code == 200) {
                        this.setData({
                            [item]: res.data.data
                        })
                    }
                }
            })
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})